package com.hyq.learn.common.response;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.hyq.learn.common.exception.errorcode.ErrorCode;

import java.util.Objects;

/**
 * @author : heyuqin
 * @since : 2024/06/27 17:06
 */
public class CommonResponse<T> {

    public static final int SUCCESS_STATE = 0;

    private Integer errorCode;

    private String errorMessage;

    private T data;

    private CommonResponse() {
    }

    private CommonResponse(Integer errorCode, T data) {
        this.errorCode = errorCode;
        this.data = data;
    }

    private CommonResponse(Integer errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    private CommonResponse(Integer errorCode, String errorMessage, T data) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
        this.data = data;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return Objects.equals(errorCode, SUCCESS_STATE);
    }

    @JsonIgnore
    public boolean isFail() {
        return !isSuccess();
    }

    public String buildFailReason() {
        return this.getErrorCode() + "," + this.getErrorMessage();
    }

    public static <T> CommonResponse<T> success() {
        return new CommonResponse<>(SUCCESS_STATE, null);
    }

    public static <T> CommonResponse<T> success(T data) {
        return new CommonResponse<>(SUCCESS_STATE, data);
    }

    public static <T> CommonResponse<T> failure(Integer errorCode, String errorMessage) {
        return new CommonResponse<>(errorCode, errorMessage);
    }

    public static <T> CommonResponse<T> failure(String errorMessage) {
        return new CommonResponse<>(-1, errorMessage);
    }

    public static <T> CommonResponse<T> failure(ErrorCode errorCode) {
        return new CommonResponse<>(errorCode.getCode(), errorCode.getMessage());
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(Integer errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
